let isEnabled = false;
let observer = null;
let isProcessing = false;

// 为所有 SVG 元素添加标记和下载按钮
function markAndAddDownloadButtons() {
    if (!isEnabled || isProcessing) return;
    isProcessing = true;
    try {
        console.log('开始标记 SVG 元素...');

        // 只处理未标记的元素
        const svgs = document.querySelectorAll('svg:not(.svg-marked)');
        const images = document.querySelectorAll('img[src$=".svg"]:not(.svg-marked), img[src*=".svg?"]:not(.svg-marked)');
        console.log('找到 SVG 元素数量：', svgs.length);
        console.log('找到 SVG 图片数量：', images.length);
        svgs.forEach((svg, index) => {
            markElement(svg, index, () => {
                return new XMLSerializer().serializeToString(svg);
            });
        });
        images.forEach((img, index) => {
            markElement(img, index, async() => {
                try {
                    const response = await fetch(img.src);
                    return await response.text();
                } catch (error) {
                    console.error('Failed to fetch SVG:', error);
                    return null;
                }
            });
        });
    } finally {
        isProcessing = false;
    }
}

// 标记元素并添加下载按钮
function markElement(element, index, getSvgContent) {
    if (!element || !element.parentElement) {
        console.log('跳过无效元素：', element);
        return;
    }

    console.log('标记元素：', element);

    // 添加标记样式
    element.classList.add('svg-marked');

    // 创建下载按钮容器
    const buttonContainer = document.createElement('div');
    if (!buttonContainer) {
        console.error('无法创建按钮容器');
        return;
    }

    buttonContainer.className = 'svg-button-container';

    // 创建下载按钮
    const downloadBtn = document.createElement('button');
    if (!downloadBtn) {
        console.error('无法创建下载按钮');
        return;
    }

    downloadBtn.className = 'svg-download-btn';
    downloadBtn.textContent = '下载 SVG';

    // 设置元素容器为相对定位
    const container = element.parentElement;
    container.style.position = 'relative';

    // 添加下载功能
    downloadBtn.addEventListener('click', async(e) => {
        e.stopPropagation();
        const svgContent = await getSvgContent();
        if (svgContent) {
            const blob = new Blob([svgContent], { type: 'image/svg+xml' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `svg-${index + 1}.svg`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }
    });

    // 将按钮添加到容器中
    buttonContainer.appendChild(downloadBtn);
    container.appendChild(buttonContainer);
}

// 清除所有标记
function clearAllMarks() {
    const markedElements = document.querySelectorAll('.svg-marked');
    markedElements.forEach(element => {
        element.classList.remove('svg-marked');
        const container = element.parentElement;
        if (container) {
            const buttonContainer = container.querySelector('.svg-button-container');
            if (buttonContainer) {
                buttonContainer.remove();
            }
        }
    });
}

// 监听来自 popup 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('收到消息：', request);
    if (request.action === 'toggleMarker') {
        isEnabled = request.enabled;
        console.log('切换标记状态：', isEnabled);

        if (isEnabled) {
            markAndAddDownloadButtons();
            // 启动观察器
            if (!observer) {
                observer = new MutationObserver((mutations) => {
                    // 只检查是否有新的 SVG 元素
                    const hasNewSvg = mutations.some(mutation => {
                        return Array.from(mutation.addedNodes).some(node => {
                            if (node.nodeType === Node.ELEMENT_NODE) {
                                return node.tagName === 'SVG' ||
                                    (node.tagName === 'IMG' &&
                                        (node.src.endsWith('.svg') || node.src.includes('.svg?')));
                            }
                            return false;
                        });
                    });

                    if (hasNewSvg) {
                        scheduleMarking();
                    }
                });
                observer.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            }
        } else {
            clearAllMarks();
            // 停止观察器
            if (observer) {
                observer.disconnect();
                observer = null;
            }
        }
        // 发送响应
        sendResponse({ success: true });
    }
    return true; // 保持消息通道开放
});

// 页面加载时检查状态
try {
    chrome.storage.local.get(['svgMarkerEnabled'], function(result) {
        console.log('初始状态：', result);
        isEnabled = result.svgMarkerEnabled || false;
        if (isEnabled) {
            markAndAddDownloadButtons();
        }
    });
} catch (error) {
    console.error('访问 storage 失败：', error);
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

const debouncedMarkAndAddDownloadButtons = debounce(markAndAddDownloadButtons, 250);